package fr.vvins.core.common.dto;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class DtoMap<K, V> implements Serializable {

    private static final long serialVersionUID = 8203462353015242759L;
    public List<DtoMapEntry<K, V>> entries;

    public DtoMap() {
        entries = new ArrayList<DtoMapEntry<K, V>>();
    }

    public void clear() {
        entries = null;
    }

    @Override
    public String toString() {
        StringBuffer buf = new StringBuffer("{");
        for (Iterator<DtoMapEntry<K, V>> it = entries.iterator(); it.hasNext();) {
            DtoMapEntry<K, V> entry = it.next();
            buf.append(entry.toString());
            if (it.hasNext()) {
                buf.append(",");
            }
        }
        buf.append("}");
        return buf.toString();
    }

    public boolean containsKey(Object key) {
        for (DtoMapEntry<K, V> entry : entries) {
            if (key.equals(entry.getKey())) {
                return true;
            }
        }
        return false;
    }

    public V get(Object key) {
        for (DtoMapEntry<K, V> entry : entries) {
            if (key.equals(entry.getKey())) {
                return entry.getValue();
            }
        }
        return null;
    }

    public Map<K, V> toMap() {
        Map<K, V> toMap = new HashMap<K, V>();
        for (K key : keySet()) {
            toMap.put(key, get(key));
        }
        return toMap;
    }

    public boolean isEmpty() {
        return entries.isEmpty();
    }

    public Set<K> keySet() {
        Set<K> keys = new HashSet<K>();
        for (DtoMapEntry<K, V> entry : entries) {
            keys.add(entry.getKey());
        }
        return keys;
    }

    public V put(K key, V value) {
        entries.add(new DtoMapEntry<K, V>(key, value));
        return value;
    }

    public void putAll(Map<? extends K, ? extends V> t) {
        for (Entry<? extends K, ? extends V> entry : t.entrySet()) {
            put(entry.getKey(), entry.getValue());
        }

    }

    public V remove(Object key) {
        for (DtoMapEntry<K, V> entry : entries) {
            if (key.equals(entry.getKey())) {
                entries.remove(entry);
                return entry.getValue();
            }
        }
        return null;
    }

    public int size() {
        return entries.size();
    }

    public Collection<V> values() {
        throw new UnsupportedOperationException("The method containsValue is not supported");
    }

}
